/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package vip.web3.api.interceptor;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import vip.web3.api.annotation.NoLogin;
import vip.web3.api.dao.biz.UserDao;
import vip.web3.api.entity.biz.UserEntity;
import vip.web3.common.exception.RRException;
import vip.web3.common.utils.RedisUtils;
import vip.web3.common.utils.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 权限(Token)验证
 *
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(AuthorizationInterceptor.class);

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        NoLogin annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(NoLogin.class);
        } else {
            return true;
        }
        if (annotation != null) {
            return true;
        }
       /* //从header中获取版本号
        String versionCode = request.getHeader("versionCode");
        //从header中获取版本号
        String appType = request.getHeader("appType");
        //如果header中不存在versionCode，则从参数中获取versionCode
        if(StringUtils.isBlank(versionCode)){
            versionCode = request.getParameter("versionCode");
        }
        if(StringUtils.isEmpty(versionCode)){
            throw new RRException("请下载最新版", 501);
        }
        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        //token为空
        if(StringUtils.isBlank(token)){
            throw new RRException("token不能为空");
        }
        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, 1);*/
        try {
            this.handlerToken();
        } catch (RRException e) {
            throw e;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Servlets.clearAuth();
    }


    private void handlerToken() {
        String token = Servlets.readToken();
        logger.info("解析到 token: {}", token);
        if (org.apache.commons.lang3.StringUtils.isBlank(token)) {
            throw new RRException("用户未登录!", 401);
        }
        String key = "alloytech:user:login:token:" + token;
        String userIdStr = redisUtils.get(key);
        if (org.apache.commons.lang3.StringUtils.isBlank(userIdStr)) {
            throw new RRException("用户未登录!", 401);
        }
        UserEntity userEntity = this.userDao.selectById(Integer.valueOf(userIdStr));
        logger.info("解析到 用户: {}", userEntity);
        if (Objects.isNull(userEntity)) {
            throw new RRException("用户未登录!", 401);
        }
        if (!userEntity.getStatus().equals(1)) {
            throw new RRException("用户未登录!", 401);
        }
        Servlets.setAuth(userEntity, token);
    }

}
